package newtank.network.server;

import code.GpcDataClientEncoder;
import code.GpcDecoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.AllArgsConstructor;
import server.netty.NettyGpcRequestHandler;

/**
 * 网络层
 * @author lijiahao
 * @since 2022/1/27
 */
@AllArgsConstructor
public class NettyServer {

    private final int port;

    public void run() throws InterruptedException {
        //用来接收进来的连接
        EventLoopGroup boosGroup = new NioEventLoopGroup(1);
        //用来处理已经被接收的连接
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap boot = new ServerBootstrap();
        boot.group(boosGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                //告诉接口如何接收连接
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        channel.pipeline()
                                .addLast(new GpcDataClientEncoder()) //编码request
                                .addLast(new GpcDecoder()) //解码response
                                .addLast(new NettyGpcRequestHandler());
                    }
                })
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true);
        // 绑定端口，开始接收进来的连接
        ChannelFuture f = boot.bind(port).sync();
        // 等待服务器socket关闭
        f.channel().closeFuture().sync();
    }
}
